//
//  AppDelegate.m
//  location
//
//  Created by Dongxiang Xu on 2024/4/12.
//

#import "AppDelegate.h"
#import "WXApi.h"
#import "LoginViewController.h"
#import "HomeViewController.h"
#import "XDXBaseTabBarViewController.h"
#import "RegisterConfigViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "WGS84TOGCJ02.h"
#import "XDXLocationManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import <CoreMotion/CoreMotion.h>
#import <UMCommon/UMCommon.h>

@interface AppDelegate ()<CLLocationManagerDelegate,WXApiDelegate,UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [WXApi registerApp:@"wxc6314a1fb0de9b3a" universalLink:@"https://m.tanhuos.com"];
    
    if (@available(iOS 13.0, *)) {
        self.window.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
    }
    if (launchOptions[UIApplicationLaunchOptionsLocationKey] || launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]){
        [XDXLocationManager shareInstance].UIApplicationLaunchOptionsLocationKey = YES;
    }else{
        [XDXLocationManager shareInstance].UIApplicationLaunchOptionsLocationKey = NO;
        
        [UMConfigure initWithAppkey:@"6699ef4dcac2a664de70c4ef" channel:@"App Store"];
        
        IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
        keyboardManager.enable = YES; // 控制整个功能是否启用。
        keyboardManager.shouldResignOnTouchOutside = YES; // 控制点击背景是否收起键盘
        keyboardManager.shouldToolbarUsesTextFieldTintColor = YES;
        keyboardManager.toolbarManageBehaviour = IQAutoToolbarBySubviews;
        keyboardManager.enableAutoToolbar = NO;
        keyboardManager.shouldShowToolbarPlaceholder = YES;
        keyboardManager.placeholderFont = [UIFont boldSystemFontOfSize:17];
        keyboardManager.keyboardDistanceFromTextField = 10.0f;
       
        [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
    }
    [XDXShareInstance shareInstance].AES = YES;
    
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:AccessToken] length]>0) {
        [XDXShareInstance shareInstance].access_token = [[NSUserDefaults standardUserDefaults] objectForKey:AccessToken];
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:FirstConfigInfo] length]>0) {
            XDXBaseTabBarViewController *tb = [[XDXBaseTabBarViewController alloc] init];
            self.window.rootViewController = tb;
            [self.window makeKeyAndVisible];
        }else {
            RegisterConfigViewController *vc = [[RegisterConfigViewController alloc] init];
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
            self.window.rootViewController = nav;
            [self.window makeKeyAndVisible];
        }
    }else{
        LoginViewController *vc = [[LoginViewController alloc] init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController = nav;
        [self.window makeKeyAndVisible];
    }
    
    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    if (![deviceToken isKindOfClass:[NSData class]]) return;
    const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
    NSString *strToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    [XDXShareInstance shareInstance].xg_token = strToken;
}

/**
 收到推送的回调
 @param application  UIApplication 实例
 @param userInfo 推送时指定的参数
 @param completionHandler 完成回调
 */
- (void)application:(UIApplication *)application
            didReceiveRemoteNotification:(NSDictionary *)userInfo
                    fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
    
{
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
}

/**
 * 用户点击推送通知时调用（最重要的方法）
 * 这是处理用户点击推送响应的核心方法
 */
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler API_AVAILABLE(ios(10.0))
{    
    if ([response.notification.request.identifier isEqualToString:@"localNotification"]) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:nil];
    }
    
    completionHandler();
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Noti_ShowMap object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:Noti_Active object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:Noti_ReloadMemberNotification object:nil]; 
    [[NSNotificationCenter defaultCenter] postNotificationName:Noti_ReloadNotification object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:Noti_Launch_Notification object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:Noti_Launch_Location object:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Noti_HideMap object:nil];
}

- (void)applicationWillResignActive:(UIApplication *)application
{   
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:FirstLaunchApp] integerValue]>0){
        if ([[XDXLocationManager shareInstance].locationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedAlways) {
            // 创建通知内容
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
            
            NSString *appDisplayName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
            if (appDisplayName == nil) {
                appDisplayName = [[NSBundle mainBundle] bundleIdentifier];
            }
            content.title = [NSString stringWithFormat:@"%@App🙋无法获得你的位置",appDisplayName];
            content.body = @"打开位置服务并设置为「始终允许」";
            content.sound = [UNNotificationSound defaultSound]; // 可选，指定声音
             
            // 创建触发器，例如延迟5秒后触发
            UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; // NO 表示不重复
             
            // 创建请求并配置触发器
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"localNotification" content:content trigger:trigger];
             
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {}];
            center.delegate = self;
            // 将请求添加到通知中心
            [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {}];
        }else if ( [[XDXLocationManager shareInstance].locationManager accuracyAuthorization]==CLAccuracyAuthorizationReducedAccuracy) {
            // 创建通知内容
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
            
            NSString *appDisplayName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
            if (appDisplayName == nil) {
                appDisplayName = [[NSBundle mainBundle] bundleIdentifier];
            }
                       
            content.title = [NSString stringWithFormat:@"%@App🙋无法获得精确位置",appDisplayName];
            content.body = @"在位置服务中打开「精确位置」";
            content.sound = [UNNotificationSound defaultSound]; // 可选，指定声音
             
            // 创建触发器，例如延迟5秒后触发
            UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO]; // NO 表示不重复
             
            // 创建请求并配置触发器
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"localNotification" content:content trigger:trigger];
             
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {}];
            center.delegate = self;
            // 将请求添加到通知中心
            [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {}];
        }
    }
}


//iOS9+，通过url scheme来唤起app
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(nonnull NSDictionary *)options
{
    if ([url.absoluteString containsString:@"safepay"]){
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSInteger status = [resultDic[@"resultStatus"] integerValue];
            if (status == 9000) {
                [[NSNotificationCenter defaultCenter] postNotificationName:Noti_Pay_Success object:nil];
            }
        }];
        return YES;
    }else{
        return [WXApi handleOpenURL:url delegate:self];
    }
}

//微信回调代理
- (void)onResp:(BaseResp *)resp
{
    if ([resp isMemberOfClass:[SendAuthResp class]])  {
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode != 0 ) {
            [[HCToast shareInstance] showToast:@"微信登录失败"];
            return;
        }
        //授权成功获取 OpenId
        NSString *code = aresp.code;
        [[NSNotificationCenter defaultCenter] postNotificationName:Noti_WXLogin object:nil userInfo:@{@"code":code}];
        [[NSNotificationCenter defaultCenter] postNotificationName:Noti_WXBling object:nil userInfo:@{@"code":code}];
    }else if ([resp isKindOfClass:[PayResp class]]){
        if (resp.errCode == WXSuccess) {
            [[NSNotificationCenter defaultCenter] postNotificationName:Noti_Pay_Success object:nil];
        }
    }else if ([resp isKindOfClass:[SendMessageToWXResp class]]){
        if (resp.errCode == WXSuccess) {
      
        }
    }
}


@end

